<?php
namespace app\common\model;

class Sms extends Base
{

	protected $insert=['create_time'];

	protected function setCreateTimeAttr(){
		return time();
	}

    /**
	 * 生成验证码
	 * @param  [type] $length [description]
	 * @return [type]         [description]
	 */
	public static function genSmsCode($length=5){
		$arr = [0,1,2,3,4,5,6,7,8,9];
		$str = '';
		for($i=1;$i<=$length;$i++){
			$str .= $arr[rand(0,9)];
		}
		return $str;
	}

	/**
	 * 验证手机验证码
	 * @param  [type] $phone [description]
	 * @param  [type] $code  [description]
	 * @return [type]        [description]
	 */
	public function checkPhoneSmsCode($phone,$smscode,$uid){
		$sms = $this -> where(['phone'=>$phone,'code'=>$smscode,'status'=>0,'uid'=>$uid])->order('create_time','desc')->find();
		if(!$sms){
			$this->error = '验证码错误';
			return false;
		}else{
			if($this->isIllegal($sms['create_time'])==false){
				$this->error = '验证码已过期';
				return false;
			}else{
				return $sms;
			}
		}
	}

	/**
	 * 验证码是否过期
	 * @return boolean [description]
	 */
	private function isIllegal($create_time){
		// 过期时间(20分钟)
		$time_range = 60*20;
		if(time()-$create_time>$time_range){
			// 过期
			return false;
		}else{
			return true;
		}
	}

}
